import React from 'react';
import _ from 'lodash';
import classNames from 'classnames';
import NumberFormatter from '@/pages/SalaryManage/components/NumberFormatter';
import DateFormatter from '@/components/DateFormatter';

import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

export class ColumnProcessor {
    constructor(columnMapper, interceptor, dataIndex, prepend, append) {
        this.columnMapper = columnMapper || {};
        this.interceptor = interceptor || (() => ({}));
        this.dataIndex = dataIndex || 'dataIndex';
        this.prepend = prepend || [];
        this.append = append || [];
    }

    merge(tableHeader = [], itemClick = () => {}) {
        const { columnMapper, dataIndex, interceptor } = this;

        const mergeList = (headerList = [], mapper, index) => {
            const result = [];

            // eslint-disable-next-line no-plusplus
            for (let i = 0; i < headerList.length; i++) {
                const header = headerList[i];
                let mergeHeader = Object.assign(_.cloneDeep(_.omit(header, 'children')), columnMapper[header[index]]);
                let extraField = {};
                if (interceptor) {
                    extraField = interceptor.apply(this, [header, dataIndex, headerList, mergeHeader, itemClick]);
                }
                mergeHeader = { ...extraField, ...mergeHeader };

                if (header.children && header.children.length > 0 && header) {
                    mergeHeader.children = mergeList(header.children);
                } else {
                    mergeHeader.children = null;
                }
                // 一级表头如果只有一个子项且没设置align,则参照子项
                if (
                    mergeHeader &&
                    !mergeHeader.align &&
                    mergeHeader.children &&
                    mergeHeader.children.length === 1 &&
                    mergeHeader.children[0].align
                ) {
                    mergeHeader.align = mergeHeader.children[0].align;
                }
                result.push(mergeHeader);
            }

            return result;
        };

        return mergeList(
            []
                .concat(this.prepend)
                .concat(tableHeader)
                .concat(this.append),
            columnMapper,
            dataIndex
        );
    }
}

const numericColumn = (header, dataIndex, mergeHeader, itemClick) => ({
    align: 'right',
    render(text, record) {
        let width = mergeHeader.width || '120px';
        if (typeof width === 'number') {
            width += 'px';
        }
        // 若小于< 0 显示红色
        return (
            <div
                // style={{ width }}
                className={classNames('p-number', salaryStyle.currency, {
                    'p-color-red': text < 0,
                    'p-hover-yellow': mergeHeader.enableClickJump === 1 && !record.$$isSummary
                })}
                onClick={() => itemClick(mergeHeader, record)}
                title={text}
            >
                <NumberFormatter value={text} negativeColor showTitle />
            </div>
        );
    }
});

// SHG员工缴交金 有可能存在多个种族，所以要特殊处理
const shgColumn = (header, dataIndex, mergeHeader, itemClick) => ({
    align: 'right',
    render(text, record) {
        let width = mergeHeader.width || '120px';
        if (typeof width === 'number') {
            width += 'px';
        }
        // 若小于< 0 显示红色
        const valList = (text || '').toString().split('/');
        const valLength = valList.length - 1;
        return (
            <div
                // style={{ width }}
                className={classNames('p-number', salaryStyle.currency, {
                    'p-color-red': text < 0,
                    'p-hover-yellow': mergeHeader.enableClickJump === 1 && !record.$$isSummary
                })}
                onClick={() => itemClick(mergeHeader, record)}
                title={text}
            >
                {valList.map((val, index) => (
                    <>
                        <NumberFormatter value={val} negativeColor showTitle />
                        <span>{index === valLength ? '' : '/'}</span>
                    </>
                ))}
            </div>
        );
    }
});

/**
 * 常用规则字段拦截器
 * @param header 后台返回来的列表头
 * @param dataIndex 数据的标识名
 * @param headerList 后台返回来的列表头数据
 * @param mergeHeader 经过初步合并后的表头
 * @returns {{}}
 * @constructor
 */
export const CommonColumnInterceptor = (header, dataIndex, headerList, mergeHeader, itemClick) => {
    let result = {
        render(text, record) {
            return record.$$isSummary ? (
                text
            ) : (
                <span title={text}>
                    <EmptyPlaceHolder value={text} />
                </span>
            );
        }
    };
    // 如果是整型或数据值, 1: 整型， 2: 数值型, 6: 种族自助金（特殊）
    if (mergeHeader.columnType === 1 || mergeHeader.columnType === 2) {
        result = {
            ...result,
            ...numericColumn(header, dataIndex, mergeHeader, itemClick, {
                decimalPlaces: mergeHeader.columnType === 1 ? 0 : 2
            })
        };
    } else if (mergeHeader.columnType === 4) {
        // 日期
        result = {
            ...result,
            width: 120,
            align: 'center',
            render(text, record) {
                return text || record.$$isSummary ? <DateFormatter value={text} /> : <EmptyPlaceHolder />;
            }
        };
    } else if (mergeHeader.columnType === 6) {
        // 种族自助金
        result = {
            ...result,
            ...shgColumn(header, dataIndex, mergeHeader, itemClick, {
                decimalPlaces: mergeHeader.columnType === 1 ? 0 : 2
            })
        };
    }

    // 如果支持排序
    if (mergeHeader.sortable) {
        result = {
            ...result,
            sortDirections: ['ascend', 'descend'],
            sorter(rowA, rowB) {
                const rowACol = rowA[mergeHeader[dataIndex]];
                const rowBCol = rowB[mergeHeader[dataIndex]];

                if (mergeHeader.columnType === 1 || mergeHeader.columnType === 2) {
                    return (rowACol || 0) - (rowBCol || 0);
                }

                return String(rowACol || '').localeCompare(rowBCol || '');
            }
        };
    }

    // 需要颜色控制
    if (mergeHeader.colorControl === 1) {
        result.className = `${result.className || ''} p-color-red`;
    }

    if (!mergeHeader?.width) {
        // 当表头文字很长时，根据文字长度设置度宽度
        const calWidth = mergeHeader.title.length * 14 + 35;

        if (calWidth > 203) {
            result.width = 203;
        } else if (calWidth > 150) {
            result.width = calWidth;
        }
    }

    result.ellipsis = true;

    return result;
};
